package controller;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

import data.Data;

@SuppressWarnings("serial")
public class ListSourceServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		HttpSession session = request.getSession();
		DBObject dbObject = (DBObject) session.getAttribute("users");
		if(dbObject==null)
		{
			try {
				response.sendRedirect("/");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		String name=request.getParameter("name");
		String work = (String)session.getAttribute("work");
		
		if(work==null)
		{
			try {
				response.sendRedirect("/manager-blog");
				return;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		String page = request.getParameter("p");
		int p = Paginate.page(page);
		int limit = 20;
		int start = (p-1)*limit;
		
		String remove=request.getParameter("remove");
		request.setAttribute("remove", remove);
		
		String falses=request.getParameter("false");
		request.setAttribute("falses", falses);
		
		DBCollection collection = Data.data("urlCraw");
		int total = 0;
		DBCursor cursor = null;
		String path="?";
		if(name==null)
		{
			cursor=collection.find(new BasicDBObject("username",dbObject.get("username")).append("blogurl", work)).skip(start).limit(limit);
			
			total = collection.find(new BasicDBObject("username",dbObject.get("username")).append("blogurl", work)).count();
		} else {
			cursor=collection.find(new BasicDBObject("username",dbObject.get("username")).append("sitemap", new BasicDBObject("$regex",name)).append("blogurl", work)).skip(start).limit(limit);
			total = collection.find(new BasicDBObject("username",dbObject.get("username")).append("sitemap", new BasicDBObject("$regex",name)).append("blogurl", work)).count();
			path="?name="+name+"&";
		}
		int np = (total%limit == 0)?total/limit:total/limit+1;
		
		request.setAttribute("total", String.valueOf(total));
		request.setAttribute("page", String.valueOf(p));
		request.setAttribute("np", String.valueOf(np));
		request.setAttribute("path", path);
		request.setAttribute("status", request.getParameter("status"));
		request.setAttribute("cursor", cursor);
		
		try {
			request.getRequestDispatcher("/list_source.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
